#include <QDebug>
#include <QFileDialog>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QSqlError>
#include <QFile>
#include <QSettings>
#include <QMessageBox>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "sqleditor.h"
#include "exportexcel2003xmldialog.h"
#include "productmanagerdialog.h"
#include "componentmanagerdialog.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // restore settings
    QSettings settings("./kintai.ini", QSettings::IniFormat);
    userID_ = settings.value("user/id", 0).toInt();
    qreal zoom = settings.value("zoom", 40.0).toDouble();
    dbName_ = settings.value("db/name", "kintai.db").toString();

    restoreGeometry( settings.value("geometry").toByteArray() );
    restoreState( settings.value("state").toByteArray() );

    // status bar
    QComboBox* zoomComboBox = new QComboBox(this);
    connect(zoomComboBox, SIGNAL(currentIndexChanged(QString)), SLOT(on_zoomComboBox_currentIndexChanged(QString)));
    for (int i=60; i>=20; --i) {
        zoomComboBox->addItem(QString("%1").arg(i));
        if (qreal(i) == zoom)
            zoomComboBox->setCurrentIndex(zoomComboBox->count()-1);
    }
    ui->statusBar->addWidget(zoomComboBox);

    // db
    setDatabase(dbName_);

    // date
    setDate( QDate::currentDate() );
}

MainWindow::~MainWindow()
{
    QSettings settings("./kintai.ini", QSettings::IniFormat);

    settings.setValue("db/name", dbName_);
    settings.setValue("user/id", userID_);

    settings.setValue("geometry", saveGeometry());
    settings.setValue("state", saveState());

    settings.setValue("zoom", ui->dailyPage->heightOfHour());

    delete ui;
}

void MainWindow::setDatabase(const QString& name)
{
    dbName_ = name;

    ui->dbNameLabel->setText(dbName_);

    db_ = QSqlDatabase::addDatabase("QSQLITE");
    db_.setDatabaseName(dbName_);
    db_.open();
    ui->dailyPage->setDatabase(db_);
    ui->weeklyPage->setDatabase(db_);
    ui->monthlyPage->setDatabase(db_);

    createTable();
    createUserList();
}

void MainWindow::createTable()
{
    const char* names[] = {
        "COMPANY",
        "USERS",
        "CLIENTUSERS",
        "PRODUCT",
        "TASKCATEGORY",
        "PRODUCTTASK",
        "COMPONENT",
        "SCHEDULED",
        "ACTUAL",
        "PRODUCTCOLOR",
        "HOLIDAY",
    };
    int n = sizeof(names) / sizeof(names[0]);

    QStringList tables = db_.tables();
    for (int i=0; i<n; ++i)
        createTableIfNeeded(tables, names[i]);
}

void MainWindow::createTableIfNeeded(const QStringList& tables, const QString& tableName)
{
    QStringList::const_iterator iter = qFind(tables, tableName);
    if (iter != tables.end())
        return;

    QFile file(":/sql/" + tableName);
    if (file.open(QIODevice::ReadOnly) == false)
        return;
    QByteArray text = file.readAll();
    QSqlQuery q = db_.exec(text);
    if (q.lastError().isValid())
        qDebug() << q.lastError().text();
}

void MainWindow::createUserList()
{
    int userID = userID_;

    ui->userComboBox->clear();
    QSqlQuery query = db_.exec("select id, name from USERS");
    while (query.next()){
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        ui->userComboBox->addItem(name, id);
        if (id == userID)
            ui->userComboBox->setCurrentIndex(ui->userComboBox->count()-1);
    }
}

void MainWindow::setDate(const QDate& date)
{
    date_ = date;
    QDate first = date.addDays(-6);
    ui->weeklyPage->setDate(first, date);
    ui->dateLabel->setText( first.toString(Qt::SystemLocaleShortDate) + " - " + date.toString(Qt::SystemLocaleShortDate) );
}

void MainWindow::on_actionSelectDatabase_triggered()
{
    QString fname = QFileDialog::getOpenFileName(this, QString(), QString(), "Database files (*.db);;All Files (*.*)");
    if (fname.isEmpty())
        return;

    setDatabase(fname);
}

void MainWindow::on_actionExportExcel2003XML_triggered()
{
    ExportExcel2003XMLDialog dlg(this, db_);
    dlg.exec();
}

void MainWindow::on_actionExit_triggered()
{
    close();
}

void MainWindow::on_actionProducts_triggered()
{
    ProductManagerDialog dlg(this, db_);
    dlg.exec();
}

void MainWindow::on_actionComponents_triggered()
{
    ComponentManagerDialog dlg(this, db_);
    dlg.exec();
}

void MainWindow::on_actionEdit_triggered()
{
    SqlEditor* editor = new SqlEditor(this, db_);
    editor->show();
}

/*!
  Help -> About menu
 */
void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::about(this, "kintai",
                       "<b>kintai tool</b><br>"
                       "1.0.4<br>"
                       "Copyright 2012-2014 Rococo Co., Ltd. All right reserved.<hr>"
                       "<a href=\"http://qt-project.org/\">Qt 4.8.1</a><br>"
                       "<a href=\"http://findicons.com/icon/237868/preferences_system_time?id=396842\">Time Icon from Oxygen Icon Pack</a>");
}

/*!
  Help -> About Qt menu
 */
void MainWindow::on_actionAboutQt_triggered()
{
    QApplication::aboutQt();
}

void MainWindow::on_userComboBox_currentIndexChanged(int index)
{
    userID_ = ui->userComboBox->itemData(index).toInt();
    ui->dailyPage->setUserID(userID_);
    ui->weeklyPage->setUserID(userID_);
    ui->monthlyPage->setUserID(userID_);
}

void MainWindow::on_todayButton_clicked()
{
    setDate( QDate::currentDate() );
}

void MainWindow::on_prevButton_clicked()
{
    setDate( date_.addDays(-1) );
}

void MainWindow::on_nextButton_clicked()
{
    setDate( date_.addDays(+1) );
}

void MainWindow::on_fastRewindButton_clicked()
{
    setDate( date_.addDays(-7) );
}

void MainWindow::on_fastForwardButton_clicked()
{
    setDate( date_.addDays(7) );
}

void MainWindow::on_zoomComboBox_currentIndexChanged(const QString& s)
{
    ui->dailyPage->setHeightOfHour(s.toDouble());
    ui->weeklyPage->setHeightOfHour(s.toDouble());
//    ui->monthlyPage->setHeightOfHour(s.toInt());
}
